package com.etoak.config.security.filter;

import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.etoak.config.security.detailservice.CustomerUserDetailService;
import com.etoak.config.security.exception.CustomerAuthenionException;
import com.etoak.config.security.handler.LoginFailureHanler;
import com.etoak.jwt.JwtUtils;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;


import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Collections;
import java.util.Map;

/**
 * @Author by 孙有泽
 * @Date 2025/2/26 9:26
 * @Description
 */
@Data
@Component("checkTokenFilter")
public class CheckTokenFilter extends OncePerRequestFilter {

    @Value("#{'${ignore.url}'.split(',')}")
    private List<String> ignoreUrl= Collections.emptyList();

    @Autowired
    private CustomerUserDetailService customerUserDetailService;
    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private LoginFailureHanler loginFailureHanler;
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        try {
            String requestURI = httpServletRequest.getRequestURI();
            if (!ignoreUrl.contains(requestURI)){
                //校验token
                validateToken(httpServletRequest);
            }
        }catch (AuthenticationException e){
            loginFailureHanler.commence(httpServletRequest,httpServletResponse,e);
            return;
        }
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
    protected  void validateToken(HttpServletRequest request){
        String token = request.getHeader("token");
        System.out.println("token"+token);
        if(StringUtils.isEmpty(token)){
            token = request.getParameter("token");
        }
        if(StringUtils.isEmpty(token)){
            throw new CustomerAuthenionException("token为空");
        }
        if(!jwtUtils.verify(token)){
            throw new CustomerAuthenionException("token无效");
        }
        DecodedJWT decodedJWT = jwtUtils.decodedJWT(token);
        Map<String, Claim> claims = decodedJWT.getClaims();
        String string = claims.get("username").asString();
        UserDetails userDetails = customerUserDetailService.loadUserByUsername(string);
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        usernamePasswordAuthenticationToken.
                setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
    }
}
